<?php
// @author AliceXT
class Cashback{
	public $countDB;
	public $sale;
	public $config;

	// 构造函数
	public function Cashback($sale){
		$this->countDB = M('cashback_count');
		$this->sale = $sale;
		$map['site_id'] = $sale['site_id'];
		$map['product_id'] = $sale['product_id'];
		$this->config = M('cashback_config')->where($map)->find();
	}

	public function canCashback(){
		$config = $this->config;
		// 是返现产品且返现功能开启
		if($config['status']){
			return true;
		}else{
			return false;
		}
	}

	// 增加返现总额、余额，调整日返率
	public function addMoney(){
		if(!$this->canCashback()){
			return false;
		}
		$sale = $this->sale;
		$config = $this->config;
		$map['member_id'] = $sale['member_id'];
		$map['product_id'] = $sale['product_id'];
		$map['rate'] = $config['rate'];
		$countDB = $this->countDB;
		$count = $countDB->where($map)->find();
		// 该用户之前没有进行返现
		if(empty($count)){
			$data['total'] = $config['total'];
			$data['rest'] = $config['total'];
			$data['rate'] = $config['rate'];
			$data['last_money'] = $config['total'];
			$data['last_adjust'] = time();
			$data['site_id'] = $sale['site_id'];
			$data['member_id'] = $sale['member_id'];
			$data['product_id'] = $sale['product_id'];
			//if($countDB->create($data)){
				$result = $countDB->add($data);
			//}
		}else{
			// 加上返现额 
			$data['total'] = $count['total']+$this->config['total'];
			$data['rest'] = $count['rest']+$this->config['total'];
			$data['rate'] = ($count['rate'] < $config['rate']) && ($count['last_money'] <= $this->config['total']) ? $config['rate'] : $count['rate'];
			$data['last_money'] = ($count['last_money'] <= $this->config['total']) ? $this->config['total'] : $count['last_money'];
			$data['last_adjust'] = ($count['last_money'] <= $this->config['total']) ? time() : $count['last_adjust'];
			// if($countDB->create($data)){ 
				$result = $countDB->where($map)->setField($data);
			// }
		}
	}

}